import { _decorator, Component, Node, resources, SpriteAtlas, Sprite, UITransform, Prefab, instantiate, Layers, randomRangeInt } from 'cc';
import { IMapInfo } from '../Interfaces';
import { DataManager } from '../manager/DataManager';
import { CocosUtils } from '../utils/CocosUtils';
import { Tile } from './Tile';
const { ccclass, property } = _decorator;

@ccclass("TileMap")
export class TileMap extends Component {

    public init(mapInfo: IMapInfo): void {
        const tilePrefab = CocosUtils.getAsset("prefab/Tile", Prefab);
        const tileAtlas = CocosUtils.getAsset("texture/tile/tile", SpriteAtlas);

        DataManager.instance.tileInfo = [];
        for (let i = 0; i < mapInfo.column; i++) {
            DataManager.instance.tileInfo[i] = [];
            let column = mapInfo.map[i];
            for (let j = 0; j < column.length; j++) {
                let item = column[j];
                if (!item.src || !item.type) {
                    continue;
                }


                let sfIndex = item.src;
                if ((item.src === 1 || item.src === 5 || item.src === 9) && (i % 2 === 0 && j % 2 === 0)) {
                    sfIndex += randomRangeInt(0, 4);
                }

                let tile = instantiate(tilePrefab);
                tile.setParent(this.node);
                let tileManager = tile.getComponent(Tile);
                tileManager.init(item.type, tileAtlas.getSpriteFrame(`tile (${sfIndex})`), i, -j);

                DataManager.instance.tileInfo[i][j] = tileManager;
            }
        }
    }
}